/**
 * Created with PyCharm.
 * User: xuhuitao
 * Date: 13-6-13
 * Time: 下午5:45
 * To change this template use File | Settings | File Templates.
 */
function LoginCtrl($scope, Login, $cookieStore) {

    $scope.pageLoad = function() {

        $scope.username = $cookieStore.get('username');
        if ($scope.username) {
            $scope.remember = true;
        }else{
            $scope.username = '';
        }
    }

    $scope.do_login = function() {

        Login.login({username:$("#username").val(), password:$("#password").val()},
            success = function(data) {

                if (data.token)  {
                    if ($scope.remember) {
                        $cookieStore.put('username', escape($scope.username));
                    } else {
                        $cookieStore.remove('username');
                    }

                    $cookieStore.put('token', escape(data.token));

                    window.location.href='/web/index.html';
                } else {
                    document.getElementById("error_message").style.display = '';
                    $scope.errorMessage = "登录失败，请与管理员联系！";
                    $("#username").focus();
                }
            },
            error = function(msg) {

                document.getElementById("error_message").style.display = '';

                if (msg.data.non_field_errors) {

                    $scope.errorMessage = "用户名或密码错误";
                    $("#username").focus();

                } else if (msg.data.username) {

                    $scope.errorMessage = "用户名必须输入";
                    $("#username").focus();
                } else if (msg.data.password) {

                    $scope.errorMessage = "密码必须输入";
                    $("#password").focus();
                } else {

                    $scope.errorMessage = "登录失败，请与管理员联系！";
                    $("#username").focus();
                }
            });
    }
};

function LogoutCtrl($rootScope, $scope, Logout, $cookieStore) {
    $scope.do_logout = function() {

        Logout.logout({},
            success = function(data) {

                $cookieStore.remove('token');

                window.location.href = "/web/login.html";
                $scope.username = $cookieStore.get('username');
            },
            error = function(msg) {

                $cookieStore.remove('token');

                window.location.href = "/web/login.html";
                $scope.username = $cookieStore.get('username');
            });
    }

    $rootScope.runactivity = true;
    $scope.toggleactivity = function(){
        $rootScope.runactivity = !$rootScope.runactivity;
    }

};